import path from './config.js'
import {
	postApi,
	getOppenId
} from './request.js'
//交换数组指定位置
const exChangeArray = function(firstIndex,secondIndex,array){
	array.splice(firstIndex - 1, 1, ...array.splice(secondIndex - 1, 1, array[firstIndex - 1]))
}
//去除url末尾分号
const delLastf = function delLastf(url) {
  if(!url){
    return;
  }
  var temp = ''
  url.split(';').forEach(item=>{
    if(item !== ''){
      temp = item
    }
  });
  // console.log("temp---------->",temp);
  return temp;
}
//公共弹窗服务
const showError = function showError(msg){
			uni.showToast({
						title:msg,
						icon: 'none',
						duration: 2000
					});
			}
//替换免费字色
const changeFontColor = function changeFontColor(font){
	var temp = [] ;
	try{
		  for(var i = 0; i < font.length; i++){
			   font[i] = font[i].replace(/免费/g,"<span style='color:#0092ff'>免费</span>");
			   temp.push(font[i]);
		  }
    }catch(e) {  
        console.log(e.message);  
    }  
	console.log("stirng---->",temp);
    return temp;  
}
//替换所有的回车换行  
const TransferString = function TransferString(content)  
{  
    var string = content;  
    try{  
        string=string.replace(/\r\n/g," ")  
        string=string.replace(/\n/g," ");  
		
    }catch(e) {  
        console.log(e.message);  
    }  
    return string;  
} 
const TransferStringBack = function TransferStringBack(content){
	var string = content
	try{
		string = string.replace(/\n/g,'\n')
	}catch(e){
		//TODO handle the exception
		console.log(e.message)
	}
	console.log('转换后的string---->',string)
	return string
}
const fmtImgUrl = function fmtImgUrl(url) {
	console.log(url);
	if(!url){
		return '';
	}
	if(url.toString().substring(0,4) == 'http'){
		console.log('http');
		return url;
	}else{
		console.log('not http');
		return path.BASE_API_NEW + url;
	}
	//现在返回全路径了
	// return path.DOWNLOAD + "?filePath=" + url + "&type=1" 
	return url
}
const fmtAudioUrl = function fmtAudioUrl(url) {
	//现在返回全路径了
	// return path.DOWNLOAD + "?filePath=" + url + "&type=2"
	return url
}
/**
 * 将http修改为https，否则ios上h5无法加载http链接的图片
 * @param {Object} url
 */
const fmtHttpUrl = function fmtHttpUrl(url) {
	if (!url.startsWith("https"))
		return url = url.replace("http", "https");
	else {
		return url;
	}
}
const upx2px = function upx2px(udp) {
	return uni.upx2px(udp) + "px";
}
const imgUrl = function imgUrl(url) {

}
const jumpToWeb = function jumpToWeb(src) {
	// #ifdef H5
	window.location.href = src
	//使用一下方法跳转，会将参数中的数据的‘+’替换成空格“ ”，导致解密失败
	// uni.navigateTo({
	// 	url: "/pages/webview/webview?src=" + encodeURIComponent(src),
	// 	animationType: "pop-in",
	// 	animationDuration: 200
	// })
	// #endif
	// #ifndef H5
	uni.navigateTo({
		url: "/pages/webview/webview?src=" + encodeURIComponent(src),
		animationType: "pop-in",
		animationDuration: 200
	})
	// #endif

}

const getSwitcher = function getSwitcher() {
	postApi(path.PUBLISH_SWITCHER, {
		id: 1
	}).then(res => {
		let data = res.data
		setIsPublishing(data[0].type == "1" ? true : false)
	})
}

//推荐跳转
const jumpToRecommendation = function jumpToRecommendation(item) {
	console.log(item.typeIdCn)
	switch (item.typeIdCn) {
		case '酒店':
			uni.navigateTo({
				url: '/pages/hotel/hoteldetail?hotelid=' + item.variousId,
				animationType: "pop-in",
				animationDuration: 200
			})
			break;
		case '餐厅':
			uni.navigateTo({
				url: '/pages/food/restaurantdetail/index?id=' + item.variousId,
				animationType: "pop-in",
				animationDuration: 200
			})
			break;
		case '美食':
			{
				var params = {
					id: item.variousId,
					page: 1,
					rows: 1
				}
				postApi(path.GET_FOODDESHES, params).then(res => {
					let data = res.data;
					console.log(JSON.stringify(data))
					if (data.success && data.rows.length > 0) {
						data.rows[0].img = data.rows[0].img;
						data.rows[0].labels = []
						if (data.rows[0].promptLabel) {
							data.rows[0].labels = data.rows[0].promptLabel.replace(new RegExp("；", "gm"), ";").split(";");
						}
						uni.navigateTo({
							url: '/pages/food/fooddetail?item=' + encodeURIComponent(JSON.stringify(data.rows[0])),
							animationType: "pop-in",
							animationDuration: 200
						})
					} else {
						uni.showToast({
							title: '没有相关数据',
							icon: 'none',
							duration: 3000
						})
					}
				})
			}
			break;
		case '景区':
			uni.navigateTo({
				url: '/pages/scence/scencedetail?id=' + item.variousId,
				animationType: "pop-in",
				animationDuration: 200
			})
			break;
		case '线路':
			{
				let isPublishing = getIsPublishing();
				console.log(isPublishing)
				if (isPublishing) {
					uni.showToast({
						title: '敬请期待...',
						icon: 'none'
					})
					return
				}
				var params = {
					businessId: item.variousId,
					page: 1,
					rows: 1
				}

				postApi(path.GET_BUSINESS_LIST, params).then(res => {
					let data = res.data;
					if (data.success && data.rows.length > 0) {
						jumpToWeb(data.rows[0].businessSrc);
					} else {
						uni.showToast({
							title: '没有相关数据',
							icon: 'none',
							duration: 3000
						})
					}
				})
			}
			break;
		case '攻略':
			{
				let isPublishing = getIsPublishing();
				if (isPublishing) {
					wx.showToast({
						title: '敬请期待...',
						icon: 'none'
					})
					return
				}

				var params = {
					strategyId: item.variousId,
					page: 1,
					rows: 1
				}
				postApi(path.GET_STRATEGY_LIST, params).then(res => {
					let data = res.data;
					if (data.success && data.rows.length > 0) {
						jumpToWeb(data.rows[0].strategySrc)
					} else {
						uni.showToast({
							title: '没有相关数据',
							icon: 'none',
							duration: 3000
						})
					}
				})
			}
			break;
	}
}

const loadProductByCategoryId = function loadProductByCategoryId(id, callback, page, rows) {
	callback = callback || function() {};
	page = page || 1;
	rows = rows || 20;
	postApi(path.GET_GOODS_BY_CATEGORY_ID, {
		categoryId: id,
		page: page,
		rows: rows
	}).then(res => {
		let data = res.data;
		console.log(data);
		if (data.success) {
			for (let i = 0; i < data.rows.length; i++) {
				//处理主图，这里作为列表图
				data.rows[i].mainImage = path.ONLINERETAILER_IMG_URL + data.rows[i].mainImage;
				//处理轮播图
				data.rows[i].banners = data.rows[i].carouselImages.replace(new RegExp('；', 'gm'), ';').replace(new RegExp(',', 'gm'), ';').replace(new RegExp('，', 'gm'), ';').split(';');
				for (let keys in data.rows[i].banners) {
					data.rows[i].banners[keys] = path.ONLINERETAILER_IMG_URL + data.rows[i].banners[keys];
				}
				//处理详情图
				data.rows[i].goodsDetails = data.rows[i].goodsDetail.replace(new RegExp('；', 'gm'), ';').replace(new RegExp(',', 'gm'), ';').replace(new RegExp('，', 'gm'), ';').split(';');
				for (let keys in data.rows[i].goodsDetails) {
					data.rows[i].goodsDetails[keys] = path.ONLINERETAILER_IMG_URL + data.rows[i].goodsDetails[keys];
				}
				//处理价格
				data.rows[i].goodsDetailVo[0].goodsPrice = data.rows[i].goodsDetailVo[0].goodsPrice.toString();
			}
			callback(data);
		} else {
			callback(data);
		}
	});
}
const getStaticResource = function getStaticResource(callback){
	callback = callback || function(res) {
	
	}
	postApi(path,{
		channelType : '1'
	}).then(res => {
		let data = res.data
		
	})
}
const getCityList = function getCityList(callback) {
	callback = callback || function(res) {

	}
	postApi(path.GET_NEW_DESTINATION_LIST, {
		channelType:1,
		pageIndex: 1,
		pageSize:100,
		centreType:"旅游目的地"
	}).then(res => {
		console.log("城市列表---------->",res.data)
		let data = res.data
		if (data.success) {
			let list = data.data.list;
			let temp = [];
			list.forEach(item => {
				temp.push({
					name:item.city
				})
			})
			console.log("城市列表push-------->",temp)
			this.setCities(temp)
			callback(temp)
		}
	})
}

//截取urL后面的参数
const getQueryString = function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

const getOpenidByJssDk = function getOpenidByJssDk(callback) {
	callback = callback || function(res) {
		console.log(JSON.stringify(res))
	}
	// #ifdef H5
	let appid = getAppid();
	let secret = getSecret();
	if (!appid && !secret) {
		callback({
			"success": false,
			"msg": ""
		})
		return
	}
	let originUrl = window.location.href;
	let code = "";
	if (window.location.href.indexOf("code") != -1) {
		code = getQueryString("code")
	}
	if (code == null || code == undefined || code == "") {
		// originUrl = "https://sz.smates.cn/onlineRetailers/destination/index.html#/pages/homepage/homepage";
		// let link =
		// 	"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+encodeURIComponent(originUrl)+"&response_type=code&scope=snsapi_userinfo&state=321#wechat_redirect"
		// window.location.href = link
		let link =
			`https://open.weixin.qq.com/connect/oauth2/authorize?
		appid=${appid}&redirect_uri=${encodeURIComponent(originUrl)}&response_type=code&scope=${'snsapi_userinfo'}&state=321#wechat_redirect`
		window.location.href = link
	} else {
		let params = {
			code: code, //要去换取openid的登录凭证
			appid: appid,
			secret: secret
		}
		getOppenId(path.WX_GET_OPENIDH5, params).then(data => {
			setOpenid(data.data.openid)
			callback({
				"success": true,
				"msg": ""
			})
		}).fail(data => {
			callback({
				"success": false,
				"msg": ""
			})
		})
	}
	// #endif
}

const isWeiXin = function isWeiXin() {
	// #ifdef H5
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
	//#endif
	return false;
}

const checkUserInfo = function checkUserInfo() {
	//如果没有登录，则跳转登录
	// let account = getAccount();
	let openid = getUserInfo().openid;
	if (!openid || openid == "") {
		// let param = {};
		// let url = "https://sz.smates.cn/app/index.html#/pages/index?page=5&param=" + encodeURIComponent(JSON.stringify(
		// 	param));
		// let to = this.$path.WWLOGIN + "?url=" + encodeURIComponent(url);
		// this.pub.jumpToWeb(to);
		uni.showModal({
			showCancel:false,
			content:"登录后可操作"
		})
		return false;
	}
	return true;
}

/**
 * 解析外部页面调用我们页面时，传过来的参数，主要获取用户信息、openid、appid、secret等信息
 * @param {Object} options
 * @param {Object} callback
 */
const parseOptions = function parseOptions(options, callback) {
	callback = callback || function(res) {
		console.log(JSON.stringify(res))
	}

	let errMsg = "";

	//如果没有传入用户信息，则判断为不是外部页面来调用,则直接返回正确
	if (!options.userinfo) {
		errMsg = "内部调用!";
		callback({
			"success": true,
			"msg": errMsg
		})
		return
	}

	if (!options.appid || options.appid == "null" || options.appid == "") {
		errMsg = "参数错误，未设置appid！";
		callback({
			"success": false,
			"msg": errMsg
		})
		return
	} else if ((!options.secret || options.appid == "null" || options.appid == "") && (!options.openid || options.openid ==
			"null" || options.openid == "") && (!options.openId || options.openId == "null" || options.openId == "")) {
		errMsg = "参数错误，未设置secret或openid！";
		callback({
			"success": false,
			"msg": errMsg
		})
		return
	} else if (options.userinfo == "null" || options.userinfo == "") {
		errMsg = "参数错误，未设置userinfo";
		callback({
			"success": false,
			"msg": errMsg
		})
		return
	}
	let params = null;
	if (options.param && options.param != "null" && options.param != "") {
		params = JSON.parse(decodeURIComponent(options.param));
	}

	//如果已经获得用户信息，则不用再请求
	let account = getAccount();
	if (account && account != "null" && account != "") {
		callback({
			"success": true,
			"msg": errMsg,
			"params": params
		})
		return
	}

	let appid = options.appid;
	let openid = options.openid || options.openId;
	let secret = options.secret;

	setAppid(appid)

	let userinfo = JSON.parse(decodeURIComponent(options.userinfo));

	// this.pub.setOpenid("wx1456c55ff4d695ba")
	// this.pub.getEncryptionOid(this.userinfo, function(res) {})
	// return;
	//如果存在openid,则不用再去自己获取openid
	if (openid && openid != "null" && openid != "") {
		setOpenid(openid);
		getEncryptionOid(userinfo, function(res) {
			if (!res) {
				errMsg = "获取用户信息失败!";
				callback({
					"success": false,
					"msg": errMsg
				})
			} else {
				//跳转具体界面
				// that.dispatch();
				errMsg = "获取用户信息成功!";
				callback({
					"success": true,
					"msg": errMsg,
					"params": params
				})
			}
		})
	} else if (secret && secret != "null" && secret != "") {
		setSecret(secret)
		//#ifdef H5
		//获取openid
		if (isWeiXin()) {
			getOpenidByJssDk(function(res) {
				if (res) {
					getEncryptionOid(userinfo, function(res) {
						if (!res.success) {
							errMsg = "获取用户信息失败!";
							callback({
								"success": false,
								"msg": errMsg
							})
						} else {
							//跳转具体界面
							// that.dispatch();
							errMsg = "获取用户信息成功!";
							callback({
								"success": true,
								"msg": errMsg,
								"params": params
							})
						}
					})
				}
			})
		} else {
			errMsg = "暂时不支持非公众号访问";
			callback({
				"success": false,
				"msg": errMsg
			})
		}
		//#endif
	}
}

const encryptUserInfo = function encryptUserInfo(phone, user, email, headImage, username,openid, callback) {
	let that = this;
	phone = phone || "";
	user = user || "";
	email = email || "";
	headImage = headImage || "";
	username = username || "";
	openid = openid || "";
	callback = callback || function(res) {
		console.log(res)
	}
	postApi(path.ENCRYPTION_RESP_INFO, {
		"phone": phone,
		"user": user,
		"email": email,
		"headImage": headImage,
		"openId":openid,
		"username": username
	}).then(res => {
		console.log(res)
		let data = res.data;
		if (data.success) {
			callback(data.exceptionInfo)
		}
	})
}

const getEncryptionOid = function getEncryptionOid(userinfo, callback) {
	callback = callback || function(data) {}

	let account = getAccount();
	if (account && account != "") {
		callback(true)
	} else if (userinfo) {
		let params = {
			data: userinfo.data,
			encryptkey: userinfo.encryptkey,
			openId: "1111111"
		}
		uni.request({
			url: path.GET_RESP_INFO,
			// url:"http://192.168.1.110:8087/resp/user",
			data: params,
			header: {
				'Content-Type': 'application/json'
			},
			method: 'POST',
			dataType: "json",
			/* 如设为json，会对返回的数据做一次 JSON.parse */
			responseType: "text",
			success: (res) => {
				console.log(JSON.stringify(res.data))
				if (res.data.success) {
					setAccount(res.data.resultData.userName)
					setOpenid(res.data.resultData.openId)
					setUser(res.data.resultData.user)
					console.log(res.data.resultData.headImge)
					setHeadImage(res.data.resultData.headImage)
				} else {
					callback(false)
					return
				}
				console.log(getAccount() + "," + getUser() + "," + getHeadImage());
				if (getAccount()) {
					callback(true)
				} else {
					uni.showToast({
						duration: 3000,
						title: "获取用户信息失败！！",
						icon: "none"
					})
					callback(false)
				}
			},
			fail: (res) => {
				console.log(res)
				callback(false)
				uni.showToast({
					duration: 3000,
					title: res,
					icon: "none"
				})
			}
		})

	} else {
		// 报错提示
		uni.showToast({
			duration: 3000,
			title: "无token信息！！",
			icon: "none"
		})
		callback(false)
	}

}

//中英文
const validChineseEnglishChar = function (target) {
	let str = target.replace(/[\u4E00-\u9FA5a-zA-Z]*/g, "");
	let str1 = target.replace(/[\s　]*/g, "");
	return str.length == 0 && str1;
}

//只能输入中文，长度不能大于2个字符
const validateNumChinese = function (target) {
	let reg = /^[\u2E80-\u9FFF]{0,2}$/;
	let str1 = target.replace(/[\s　]*/g, "");
	return reg.test(target) && str1
}

//验证电话号码
const validatePhone = function (target) {
	let cellPhone = /^1(3|4|5|7|8)\d{9}$/;
	let telPhone = /^\d{4}-\d{5,7}$/;
	let phone = /^400[-\d]{7}/;
	return cellPhone.test(target) || telPhone.test(target) || phone.test(target);
}

const getLog = function getLog() {
	try {
		return uni.getStorageSync("log")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setLog = function setLog(log) {
	try {
		return uni.setStorageSync("log", log)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getUserInfo = function getUserInfo() {
	try {
		return uni.getStorageSync("userinfo")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setUserInfo = function setUserInfo(userinfo) {
	try {
		return uni.setStorageSync("userinfo", userinfo)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}
const getUserIntegral = function getUserIntegral() {
	try {
		return uni.getStorageSync("userintegral")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setUserIntegral = function setUserIntegral(userinfo) {
	try {
		return uni.setStorageSync("userintegral", userinfo)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}
/**
 * 获取保存好的用户账号
 */
const getAccount = function getAccount() {
	try {
		return uni.getStorageSync("account")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setAccount = function setAccount(account) {
	try {
		return uni.setStorageSync("account", account)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getHeadImage = function getHeadImage() {
	try {
		return uni.getStorageSync("headimage")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setHeadImage = function setHeadImage(headimge) {
	try {
		return uni.setStorageSync("headimage", headimge)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setMemberId = function setMemberId(memberid){
	try {
		return uni.setStorageSync("memberid", memberid)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}
const getMemberId = function getMemberId(){
	try {
		return uni.getStorageSync("memberid")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}
const getUser = function getUser() {
	try {
		return uni.getStorageSync("user")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setUser = function setUser(user) {
	try {
		return uni.setStorageSync("user", user)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getAppid = function getAppid() {
	try {
		return uni.getStorageSync("appid")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setAppid = function setAppid(appid) {
	try {
		return uni.setStorageSync("appid", appid)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getOrigin = function getOrigin() {
	try {
		return uni.getStorageSync("origin")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setOrigin = function setOrigin(origin) {
	try {
		return uni.setStorageSync("origin", origin)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getSecret = function getSecret() {
	try {
		return uni.getStorageSync("secret")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setSecret = function setSecret(secret) {
	try {
		return uni.setStorageSync("secret", secret)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getOpenid = function getOpenid() {
	try {
		return uni.getStorageSync("openid")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setOpenid = function setOpenid(openid) {
	try {
		return uni.setStorageSync("openid", openid)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getToken = function getToken() {
	try {
		return uni.getStorageSync("token")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setToken = function setToken(token) {
	try {
		return uni.setStorageSync("token", token)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setCities = function setCities(cities) {
	try {
		return uni.setStorageSync("cities", cities)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getCities = function getCities() {
	try {
		return uni.getStorageSync("cities")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setIsPublishing = function setIsPublishing(isPublishing) {
	try {
		return uni.setStorageSync("isPublishing", isPublishing)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getIsPublishing = function getIsPublishing() {
	try {
		return uni.getStorageSync("isPublishing")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setLocalcity = function setLocalcity(localcity) {
	try {
		return uni.setStorageSync("localcity", localcity)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getLocalcity = function getLocalcity() {
	try {
		return uni.getStorageSync("localcity")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const setAddress = function setAddress(address) {
	try {
		return uni.setStorageSync("address", address)
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const getAddress = function getAddress() {
	try {
		return uni.getStorageSync("address")
	} catch (e) {
		//TODO handle the exception
		return null;
	}
}

const channelType = '5'
const appId = 'wx813a8c0dfd0f6ad5'
module.exports = {
	appId,
	channelType,
	fmtImgUrl,
	fmtAudioUrl,
	fmtHttpUrl,
	jumpToWeb,
	getSwitcher,
	getQueryString,
	getEncryptionOid,
	encryptUserInfo,
	parseOptions,
	getOpenidByJssDk,
	isWeiXin,
	getToken,
	setLog,
	getLog,
	getOpenid,
	getSecret,
	setUserInfo,
	getUserInfo,
	getUserIntegral,
	setUserIntegral,
	getAccount,
	getOrigin,
	setOrigin,
	getUser,
	setUser,
	setHeadImage,
	getHeadImage,
	getAppid,
	setToken,
	setOpenid,
	setSecret,
	setAccount,
	setAppid,
	getAddress,
	setAddress,
	checkUserInfo,
	jumpToRecommendation,
	getCities,
	setCities,
	getIsPublishing,
	setIsPublishing,
	getLocalcity,
	setLocalcity,
	getCityList,
	loadProductByCategoryId,
	upx2px,
	TransferString,
	TransferStringBack,
	validChineseEnglishChar,
	validateNumChinese,
	validatePhone,
	changeFontColor,
	showError,
	delLastf,
	setMemberId,
	getMemberId,
	exChangeArray
}
